package com.hmall.trade.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.api.cart.CartClient;
import com.hmall.api.item.ItemClient;
import com.hmall.api.item.dto.ItemDTO;

import com.hmall.api.item.dto.OrderDetailDTO;
import com.hmall.api.pay.PayClient;

import com.hmall.common.constants.MqConstants;
import com.hmall.common.exception.BadRequestException;
import com.hmall.common.utils.UserContext;


import com.hmall.mq.client.RabbitClient;
import com.hmall.mq.config.RabbitMqAutoConfiguration;
import com.hmall.trade.domain.dto.OrderFormDTO;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.domain.po.OrderDetail;
import com.hmall.trade.mapper.OrderMapper;
import com.hmall.trade.service.IOrderDetailService;
import com.hmall.trade.service.IOrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2023-05-05
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    //private final IItemService itemService;
    private final IOrderDetailService detailService;
    //private final ICartService cartService;

    private final CartClient cartClient;


    private final ItemClient itemClient;

    private final RabbitTemplate rabbitTemplate;

    private final PayClient payClient;

    private final RabbitClient rabbitClient;

    @Override
    @GlobalTransactional
    public Long createOrder(OrderFormDTO orderFormDTO) {
        // 1.订单数据
        Order order = new Order();
        // 1.1.查询商品
        List<OrderDetailDTO> detailDTOS = orderFormDTO.getDetails();
        // 1.2.获取商品id和数量的Map
        Map<Long, Integer> itemNumMap = detailDTOS.stream()
                .collect(Collectors.toMap(OrderDetailDTO::getItemId, OrderDetailDTO::getNum));
        Set<Long> itemIds = itemNumMap.keySet();
        // 1.3.查询商品
        List<ItemDTO> items = itemClient.queryItemByIds(itemIds);
        if (items == null || items.size() < itemIds.size()) {
            throw new BadRequestException("商品不存在");
        }
        // 1.4.基于商品价格、购买数量计算商品总价：totalFee
        int total = 0;
        for (ItemDTO item : items) {
            total += item.getPrice() * itemNumMap.get(item.getId());
        }
        order.setTotalFee(total);
        // 1.5.其它属性
        Long userId = UserContext.getUser();
        order.setPaymentType(orderFormDTO.getPaymentType());
        order.setUserId(userId);
        order.setStatus(1);
        // 1.6.将Order写入数据库order表中
        save(order);

        // 2.保存订单详情
        List<OrderDetail> details = buildDetails(order.getId(), items, itemNumMap);
        detailService.saveBatch(details);

        // 3.清理购物车商品
        Map<String,Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("itemIds", itemIds);
        try {
            rabbitTemplate.convertAndSend(MqConstants.TRADE_EXCHANGE_NAME, MqConstants.ORDER_CREATE_KEY, map);
        } catch (AmqpException e) {
            log.error("清理购物车的消息发送失败：{}", e);
        }
        //cartClient.deleteCartItemByIds(userId,itemIds);

        // 4.扣减库存
        try {
            itemClient.deductStock(detailDTOS);
        } catch (Exception e) {
            throw new RuntimeException("库存不足！");
        }
//        int i = 1;
//        if(i!=0){
//            throw new RuntimeException("报错");
//        }



        rabbitClient.sendMsg(MqConstants.DELAY_EXCHANGE_NAME, MqConstants.DELAY_ORDER_KEY,order,10000,null,false);

//        rabbitTemplate.convertAndSend(MqConstants.DELAY_EXCHANGE_NAME, MqConstants.DELAY_ORDER_KEY, order.getId(), new MessagePostProcessor() {
//            @Override
//            public Message postProcessMessage(Message message) throws AmqpException {
//                //添加延迟消息属性
//                message.getMessageProperties().setDelay(10000);
//                log.info("发送消息"+new String(message.getBody(), StandardCharsets.UTF_8)+ LocalDateTime.now());
//                return message;
//            }
//        });
        return order.getId();
    }

    @Override
    public void markOrderPaySuccess(Long orderId) {
        Order order = new Order();
        order.setId(orderId);
        order.setStatus(2);
        order.setPayTime(LocalDateTime.now());
        updateById(order);
    }

    /**
     * 取消订单，回滚库存
     * @param orderId
     */
    @Override
    public void cancelOrder(Long orderId) {
        //查询需要取消的订单
        Order order = getById(orderId);
        //取消订单
        lambdaUpdate().eq(Order::getId, orderId)
                .eq(Order::getStatus, 1)
                .set(Order::getStatus, 5)
                .set(Order::getCloseTime, LocalDateTime.now())
                .update();
        //同步修改支付单状态
        payClient.updatePayOrder(orderId);
        //回滚库存
        List<OrderDetail> orderDetails = detailService
                .list(Wrappers.<OrderDetail>lambdaQuery()
                .eq(OrderDetail::getOrderId, orderId));
        List<OrderDetailDTO> orderDetailDTOS = new ArrayList<>();
        orderDetails.forEach(orderDetail -> {
            Integer num = orderDetail.getNum();
            OrderDetailDTO dto = new OrderDetailDTO();
            dto.setNum(-num);
            dto.setItemId(orderDetail.getItemId());
            orderDetailDTOS.add(dto);
        });
        itemClient.deductStock(orderDetailDTOS);
    }

    private List<OrderDetail> buildDetails(Long orderId, List<ItemDTO> items, Map<Long, Integer> numMap) {
        List<OrderDetail> details = new ArrayList<>(items.size());
        for (ItemDTO item : items) {
            OrderDetail detail = new OrderDetail();
            detail.setName(item.getName());
            detail.setSpec(item.getSpec());
            detail.setPrice(item.getPrice());
            detail.setNum(numMap.get(item.getId()));
            detail.setItemId(item.getId());
            detail.setImage(item.getImage());
            detail.setOrderId(orderId);
            details.add(detail);
        }
        return details;
    }


}
